package net.qiqbframework.modelling.repository;

import net.qiqbframework.messaging.task.CurrentMessageTask;
import net.qiqbframework.messaging.task.MessageTask;
import net.qiqbframework.modelling.domain.Aggregate;

import java.util.*;

public class RepositoryContext {

    public static <T> Optional<Aggregate<T>> aggregate(String aggregateNaming, String bizIdentifierNaming, Object bizIdentifier) {
        final MessageTask<?> messageTask = CurrentMessageTask.get();
        final Map<String, Aggregate<?>> aggregateCache = messageTask.root().getOrComputeResource("__AggregateCache", (key) -> new HashMap<>());

        return Optional.empty();
    }

    /**
     * 将加载的信息缓存
     *
     * @param aggregate
     */
    public static void cachingAggregate(Aggregate<?> aggregate) {
        final Map<String, Aggregate<?>> aggregateCache = getStringAggregateMap();
        // 找这个所有的
        //aggregateCache.put()
    }

    private static Map<String, Aggregate<?>> getStringAggregateMap() {
        final MessageTask<?> messageTask = CurrentMessageTask.get();
        final Map<String, Aggregate<?>> aggregateCache = messageTask.root().getOrComputeResource("__AggregateCache", (key) -> new HashMap<>());
        return aggregateCache;
    }

    /**
     * 如果命令中只能确认对于的聚合类型，
     *
     * @param aggregateNaming
     * @param <T>
     * @return
     */
    public static  List<Aggregate<?>> aggregateFromAggregateNaming(String aggregateNaming) {
        final Map<String, Aggregate<?>> aggregateCache = getStringAggregateMap();
        Set<Aggregate<?>> matched = new HashSet<>();
        for (Map.Entry<String, Aggregate<?>> entry : aggregateCache.entrySet()) {
            if (entry.getKey().startsWith(aggregateNaming)) {
                matched.add(entry.getValue());
            }
        }

        return matched.stream().toList();
    }
}
